package slu.appli.wodtimer;

import java.util.ArrayList;
import java.util.List;

public class ItemTimer {
	private static final int ELAPSE_FOR_LISTENER = 1000;
	
	private long elapse = 0;
	private boolean stopped = false;
	private List<ItemTimerListenerInterface> listeners = new ArrayList<ItemTimerListenerInterface>();

	public ItemTimer(String elapse) {
		super();
		this.elapse = Long.parseLong(elapse) * 1000;
	}

	public ItemTimer(long elapse) {
		super();
		this.elapse = elapse;
	}
	
	public long processTimer(long startTime) {
		this.stopped = false;
		long currentTime = System.currentTimeMillis();
		long endTime = (startTime == 0 ? currentTime + this.elapse: startTime + this.elapse);
		while (System.currentTimeMillis() <= endTime) {
			try {
				Thread.sleep(50);
				if (System.currentTimeMillis() - currentTime >= ItemTimer.ELAPSE_FOR_LISTENER) {
					currentTime += ItemTimer.ELAPSE_FOR_LISTENER;
					this.fireElapseDone();
				}
				if (this.stopped) break;
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		return endTime;
	}

	public long getElapse() {
		return elapse;
	}
	
	public void stop() {
		this.stopped = true;
	}
	
	public void addItemTimerListener(ItemTimerListenerInterface listener) {
		this.listeners.add(listener);
	}
	
	public void removeItemTimerListener(ItemTimerListenerInterface listener) {
		this.listeners.remove(listener);
	}
	
	private void fireElapseDone() {
		for(ItemTimerListenerInterface listener : this.listeners) {
			listener.elapseDone();
		}
	}
	
}
